package basic.courseLearn09.problem;

import org.junit.Test;

import java.util.Stack;

//逆序栈问题
public class ReverseStack {

    @Test
    public void test(){
        Stack<Integer> stack = new Stack<>();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        System.out.println(stack);
        reverse(stack );
        System.out.println(stack);
    }


    /**
     * 返回最底层的元素
     * @param stack 栈
     * @return
     */
    public int returnLastOne(Stack<Integer> stack){
        //1. 递归截止条件，栈中只有一个元素
        if (stack.size() == 1){
            return stack.pop();
        }
        //2. 递归调用，返回最底层的元素
        int x = stack.pop();
        int y = returnLastOne(stack);
        stack.add(x);
        return y;
    }


    /**
     * 反转栈
     * @param stack 栈
     */
    public void reverse(Stack<Integer> stack){
        if (stack.size()==1){
            return;
        }
        int x = returnLastOne(stack);
        reverse(stack);
        stack.add(x);

    }








}
